<template>
  <a-modal
    :title="type ? '编辑群组' : '新增群组'"
    :visible.sync="visible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        label="名称"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="[
            'name',
            {
              initialValue: editInfo.name,
              rules: [
                {
                  required: true,
                  message: '请输入名称！'
                },
                {
                  validator: $validate.validateLength,
                  max: 50,
                  min: 1
                }
              ]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="管理员/ID"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-select
          v-decorator="[
            'admin_id',
            {
              initialValue: editInfo.admin_id,
              rules: [{ required: true, message: '必选项' }]
            }
          ]"
        >
          <a-select-option
            v-for="(item, index) in addInfo.adminInfo"
            :key="index"
            :value="item.id"
          >
            {{ item.username }}/{{ item.id }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="群组分类"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-select
          v-decorator="[
            'group_cat_id',
            {
              initialValue: editInfo.group_cat_id,
              rules: [{ required: true, message: '必选项' }]
            }
          ]"
        >
          <a-select-option
            v-for="(item, index) in addInfo.groupCatInfo"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="封面图"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        help="建议图片宽高为：162px*162px"
      >
        <div class="clearfix">
          <a-upload
            v-decorator="[
              'cover',
              {
                initialValue: editInfo.upload,
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                rules: [{ required: true, message: '请上传封面图' }]
              }
            ]"
            accept="image/*"
            listType="picture-card"
            name="file"
            :multiple="false"
            :showUploadList="false"
            :action="$api.upload"
            :data="postData"
            :beforeUpload="beforeUpload"
          >
            <img
              v-if="imageUrl"
              :src="$api.picPre + imageUrl"
              alt="avatar"
              style="width: 120px"
            />
            <div v-else>
              <a-icon :type="bgLoading ? 'bgLoading' : 'plus'" />
              <div class="ant-upload-text">上传封面图</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>
      <a-form-item
        label="背景图"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        help="建议图片宽高为：375px*201px"
      >
        <div class="clearfix">
          <a-upload
            v-decorator="[
              'background_img',
              {
                initialValue: editInfo.uploadbg,
                valuePropName: 'fileList',
                getValueFromEvent: normFileBg,
                rules: [{ required: true, message: '请上传背景图' }]
              }
            ]"
            accept="image/*"
            listType="picture-card"
            name="file"
            :multiple="false"
            :showUploadList="false"
            :action="$api.upload"
            :data="postDataBg"
            :beforeUpload="beforeUploadBg"
          >
            <img
              v-if="imageBgUrl"
              :src="$api.picPre + imageBgUrl"
              alt="avatar"
              style="width: 120px"
            />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传背景图</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>
      <a-form-item
        label="简介"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-textarea
          v-decorator="[
            'describe',
            {
              initialValue: editInfo.describe,
              rules: [
                {
                  required: true,
                  message: '请输入简介！'
                },
                {
                  validator: $validate.validateLength,
                  max: 200,
                  min: 1
                }
              ]
            }
          ]"
          placeholder=""
          :rows="3"
        />
      </a-form-item>
      <a-form-item
        label="入群经验值"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-input
          v-decorator="[
            'experience',
            {
              initialValue: editInfo.experience,
              rules: [{ required: true, message: '请输入入群经验值！' }]
            }
          ]"
        />
      </a-form-item>
      <a-form-item
        label="认投项目"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-select
          v-decorator="[
            'project_id',
            {
              initialValue: editInfo.project_id
            }
          ]"
        >
          <a-select-option
            v-for="(item, index) in addInfo.project"
            :key="index"
            :value="item.id"
          >
            {{ item.project_name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="是否推荐"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-select
          v-decorator="[
            'is_recommend',
            {
              initialValue: editInfo.is_recommend,
              rules: [{ required: true, message: '必选项' }]
            }
          ]"
        >
          <a-select-option value="2">
            推荐
          </a-select-option>
          <a-select-option value="1">
            不推荐
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { getToken } from "@/tool/qiniu";
export default {
  name: "add",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: Number,
      default: 0
    },
    info: {
      type: Object
    },
    edit: {
      type: Object
    }
  },
  data() {
    this.handleSubmit = this.$debounce(this.handleSubmit, 800);
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      addInfo: {},
      editInfo: {},
      initInfo: {
        upload: [],
        uploadbg: []
      },
      postData: {
        token: ""
      },
      postDataBg: {
        token: ""
      },
      loading: false,
      bgLoading: false,
      imageUrl: "",
      imageBgUrl: ""
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          let api = null;
          if (this.type === 0) {
            api = this.$api.addGroup;
          } else {
            api = this.$api.saveGroup;
            values.id = this.editInfo.id;
          }
          for (let item of this.addInfo.adminInfo) {
            if (values.admin_id === item.id) {
              values.admin_name = item.username;
            }
          }
          if (values.cover) {
            values.cover = values.cover[0].response.key;
          }
          if (values.background_img) {
            values.background_img = values.background_img[0].response.key;
          }
          this.$ajax
            .post(api, values)
            .then(() => {
              this.$notification.success({
                message: "操作成功！"
              });
              this.handleCancel(true);
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        }
      });
    },
    handleCancel(isFresh) {
      this.form.resetFields();
      this.$emit("handleCancel", isFresh);
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    normFileBg(e) {
      if (e.file.status === "uploading") {
        this.bgLoading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageBgUrl = e.file.response.key;
        this.bgLoading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "group/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 162;
        let height = 162;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为162px*162px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    beforeUploadBg(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "groupBg/" + timestamp2 + "." + type;
      this.postDataBg.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 375;
        let height = 201;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为375px*201px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    }
  },
  created() {},
  watch: {
    info: {
      handler: function(val) {
        this.addInfo = JSON.parse(JSON.stringify(val));
      },
      deep: true
    },
    edit: {
      handler: function(val) {
        this.editInfo = JSON.parse(JSON.stringify(val));
        this.imageBgUrl = this.editInfo.background_img;
        this.imageUrl = this.editInfo.cover;
      },
      deep: true
    }
  }
};
</script>

<style scoped></style>
